<route>
    {
        meta: {
            layout: 'index',
            title:'非常规作业许可'
        }
    }  
</route>
<template>
  <div>
    <AntdZh>
      <a-card>
        <div>
          <a-row v-if="selectedReport">
            <a-button type="primary" style="margin-left: auto; margin-bottom: 10px; margin-right: 10px; width: 100px"
              @click="doReturn">返回</a-button>
          </a-row>
        </div>
        <div v-if="!selectedReport">
          <a-tabs v-model:activeKey="activeKey">
            <a-tab-pane key="1" tab="信息录入">
              <div>
                <a-form :model="params" name="basic" :label-col="{ span: 10 }">
                  <a-card>
                    <template #title>
                      <span>填报单位：<span style="color: green">
                          <a-select v-model:value="params.unit" style="width: 220px">
                            <a-select-option v-for="item of unit" :value="item" :key="item"> {{ item }}</a-select-option>
                          </a-select></span>
                      </span>
                    </template>
                    <a-row>
                      <a-col :span="8">
                        <a-form-item label="作业申请时间" name="requestTime">
                          <a-date-picker v-model:value="params.requestTime" style="width: 170px" placeholder="作业申请时间" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="作业区域所在单位" name="unit_located">
                          <a-select v-model:value="params.unit_located" style="width: 170px">
                            <a-select-option v-for="item of unit" :value="item" :key="item"> {{ item }}</a-select-option>
                          </a-select>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="属地监督" name="territorial_oversight">
                          <UsersSelect :role="'属地监督'" style="width: 170px" @getUser="getUser"></UsersSelect>
                        </a-form-item>
                      </a-col>
                    </a-row>
                    <a-row>
                      <a-col :span="8">
                        <a-form-item label="监护人" name="guardian">
                          <UsersSelect :role="'监护人'" style="width: 170px" @getUser="getUser"></UsersSelect>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="申请人" name="applicant">
                          <UsersSelect :role="'申请人'" style="width: 170px" @getUser="getUser"></UsersSelect>
                        </a-form-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-item label="作业人" name="operator">
                          <UsersSelect :role="'作业人'" style="width: 170px" @getUser="getUser"></UsersSelect>
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </a-card>
                  <a-card style="margin-top: 10px">
                    <template #title>
                      <span>非常规 / 特殊规作业：<span style="color: green"></span>
                        <a-select v-model:value="params.involves_special_operations" style="width: 230px"
                          placeholder="涉及的其他非常规作业、特殊作业">
                          <a-select-option v-for="item of unconventionalTasks" :value="item" :key="item">
                            {{ item }}</a-select-option>
                        </a-select></span>
                    </template>
                    <a-row>
                      <a-col :span="8">
                        <a-form-item label="作业许可证编号" name="other_unroutine_operations">
                          <a-input v-model:value="params.other_unroutine_operations" style="width: 300px"
                            placeholder="涉及的其他非常规作业、特殊作业许可证编号" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="14">
                        <a-form-item label="作业地点" name="wellId">
                          <a-input v-model:value="auxiliary.wellId" style="width: 300px" placeholder="请输入作业地点" />
                          <!-- <a-select v-model:value="auxiliary.wellId" style="width: 330px">
                          <a-select-option v-for="item of operationPlace" :value="item" :key="item">
                            {{ item }}</a-select-option>
                        </a-select> -->
                        </a-form-item>
                      </a-col>
                    </a-row>
                    <a-row>
                      <a-col :span="8">
                        <a-form-item label="作业部门" name="tasksDepartment">
                          <a-select v-model:value="auxiliary.tasksDepartment" style="width: 300px">
                            <a-select-option v-for="item of tasksDepartment" :value="item" :key="item">
                              {{ item }}</a-select-option>
                          </a-select>
                        </a-form-item>
                      </a-col>
                      <a-col :span="14">
                        <a-form-item label="作业内容" name="job_content">
                          <a-select v-model:value="params.job_content" style="width: 300px">
                            <a-select-option v-for="item of unconventionalTasks" :value="item" :key="item">
                              {{ item }}</a-select-option>
                          </a-select>
                        </a-form-item>
                      </a-col></a-row>
                  </a-card>
                  <a-card style="margin-top: 10px">
                    <template #title>
                      <span>编制方案
                        <span style="color: green">
                          <a-switch v-model:checked="params.programming" checked-children="是" un-checked-children="否"
                            style="width: 100px" /> </span></span>
                    </template>
                    <a-row>
                      <!-- <a-col :span="6">
                      <a-form-item label="作业内容签名" name="job_content_signature" style="margin-left: 73px">
                        <a-input
                          v-model:value="params.job_content_signature"
                          style="width: 200px"
                          placeholder="针对作业内容签名"
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :span="6">
                      <a-form-item label="签字时间" name="job_content_date" style="margin-left: 108px">
                        <a-date-picker
                          v-model:value="params.job_content_date"
                          format="YYYY-MM-DD"
                          style="width: 200px"
                          placeholder="签字时间"
                        />
                      </a-form-item>
                    </a-col> -->
                      <a-col :pull="5" :span="20"><a-form-item label="作业时间" name="terminate_time">
                          <a-space direction="vertical" :size="12">
                            <AntdZh><a-range-picker v-model:value="workTime" style="width: 330px" /></AntdZh>
                          </a-space>
                        </a-form-item>
                      </a-col>
                      <a-col :pull="5" :span="20">
                        <a-form-item label="存在的风险" name="existential_risks">
                          <a-checkbox-group v-model:value="existential_risks" name="checkboxgroup" :options="plainOptions"
                            style="width: 100vh" />
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </a-card>
                </a-form>
                <a-divider />
              </div>
              <a-button type="primary" style="width: 100%" @click="getSubmit">提交</a-button>
            </a-tab-pane>
            <a-tab-pane key="2" tab="上传记录">
              <HistoryInfo  @editInfo="editInfo"></HistoryInfo>
            </a-tab-pane>
            <a-tab-pane key="3" tab="审批任务" v-if="isSuper || isExam">
              <Approval  @editInfo="editInfo"></Approval>
            </a-tab-pane>
          </a-tabs>
        </div>
        <view v-if="selectedReport">
          <WorkPermitDetail :reportId="selectedReport"></WorkPermitDetail>
        </view>
      </a-card>
    </AntdZh>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { createLicence, updateOne, queryList } from "@/api/salvage/workPermit.js";
import { unconventionalTasks, tasksDepartment, unit, plainOptions } from "@/custom/salvage/constant/report.js";
import HistoryInfo from "../workPermit/drawer/historyInfo.vue";
import Approval from "../workPermit/drawer/Approval.vue";
import WorkPermitDetail from "./detail";
import FlowWorks from "@/api/flow/works";
import "dayjs/locale/zh-cn";
import dayjs from "dayjs";
import useApp from "@/hooks";
import UsersSelect from "@/custom/salvage/components/UsersSelect.vue";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const { $, proxy } = useApp();
// const result = ref(null);
const activeKey = ref("1");
const selectedReport = ref(false);
// const defaultParams = ref($.freeStore(params.value));
const auxiliary = ref({
  wellId: "",
  tasksDepartment: "",
});
const params = ref({
  unit: "测井项目部",
  requestTime: dayjs(),
  unit_located: "测井项目部",
  territorial_oversight: "",
  guardian: "",
  applicant: "",
  operator: "",
  involves_special_operations: "不带源仪器穿心解卡",
  other_unroutine_operations: "",
  wellId: "",
  job_content: "",
  job_content_signature: "",
  job_content_date: "",
  programming: true,
  start_time: "",
  terminate_time: "",
  existential_risks: "",
});
const FlowParams = ref({
  businessId: "",
  businessName: "作业许可",
  businessType: "作业许可",
  flowCode: "workPermit-check",
  flowName: "复杂处置非常规作业许可审核",
  flowParam: "",
  initiator: "",
  rootFlowId: ""
})
const workTime = ref();
const existential_risks = ref([]);
const open = ref(false);
const isSuper = ref(userStore.isAdmin)
const isExam = ref()
const query = ref({ 
  order: "DESC", 
  pageNum: "1", 
  pageSize: "99999", 
  sortBy: "id", 
  initiator: '' 
})
watch(() => activeKey.value, () => {
  // 角色限制
  onLoad()
  //历史信息
  // FlowWorks.queryList(query.value).then((res) => {
  //   console.log("watch-历史记录", res);
  //   result.value = res.content;
  //   if (result.value.length !== 0) {
  //     result.value.forEach(element => {
  //       element.unit = JSON.parse(element.flowParam).unit
  //       element.wellId = JSON.parse(element.flowParam).wellId
  //     });
  //   }
  // });
});
function onLoad() {
  // 角色限制
  let uid = localStorage.getItem("userId");
  let userName = localStorage.getItem("userName")
  if (userStore.isAdmin !== true) { //不是超级管理员情况
    query.value.initiator = uid;
    // 审查权限
    if (userName == 'wellzypzr' || userName == 'wellsdjd' || userName == 'welljhr') {
      isExam.value = true
    } else {
      isExam.value = false
    }
  }
}
onLoad()
// 获取审批人信息
function getUser(e) {
  // console.log('getUser', e);
  if (e.role == "属地监督") {
    params.value.territorial_oversight = e.nickName;
  } else if (e.role == "申请人") {
    params.value.applicant = e.nickName;
  } else if (e.role == "监护人") {
    params.value.guardian = e.nickName;
  } else if (e.role == "作业人") {
    params.value.operator = e.nickName;
  }
}
// 提交
function getSubmit() {
  params.value.wellId = auxiliary.value.wellId + "(" + auxiliary.value.tasksDepartment + ")";
  params.value.existential_risks = existential_risks.value.join(",");
  // 日期格式化
  // if (params.value.requestTime) { params.value.requestTime = dayjs(params.value.requestTime).format("YYYY-MM-DD"); }
  if (params.value.job_content_date) { params.value.job_content_date = dayjs(params.value.job_content_date).format("YYYY-MM-DD"); }
  if (workTime.value) {
    params.value.start_time = dayjs(workTime.value[0]).format("YYYY-MM-DD");
    params.value.terminate_time = dayjs(workTime.value[1]).format("YYYY-MM-DD");
  }
  console.log("getSubmit", params.value);
  createLicence(params.value.wellId).then((res) => {
    // localStorage.setItem("schemeId", res.id);
    // localStorage.setItem("wellId", res.wellId);
    console.log("createSchemes", res);
    FlowParams.value.businessId = res.id
    FlowParams.value.flowParam = JSON.stringify(params.value);
    FlowParams.value.initiator = res.createUserId
    updateOne(res.id, params.value).then((e) => {
      $.showToast({
        title: "方案新建成功",
        icon: "success",
      });
      open.value = false;
      console.log("updateOne", e);
      selectedReport.value = res.id;
      // console.log('FlowParams.value', FlowParams.value);
      FlowWorks.queryStart(FlowParams.value).then(response => {
        console.log('流程发起', response);
      })
    });
    resetParams(params.value);
  });
}

// 重置params对象
function resetParams(obj) {
  for (let key in obj) {
    if (Array.isArray(obj[key])) {
      // console.log('重置params数组', obj[key]);
      obj[key] = []; // 清空数组
    } else {
      obj[key] = null; // 重置属性
    }
  }
  existential_risks.value = [];
}
// 返回
function doReturn() {
  selectedReport.value = false;
  resetParams(params.value);
}
function openDrawer() {
  open.value = true;
}
defineExpose({
  openDrawer: openDrawer,
});
</script>
